import { Injectable } from '@angular/core';
import { HttpService } from './http.service';
import * as ons from 'onsenui';


interface Gugu {
  requestSent?: Boolean,
  data: any
}

@Injectable()
export class CarService {
  banner: Gugu = {requestSent: false, data:[]}
  car: Gugu = {requestSent: false, data:[]}
  order: Gugu = {requestSent: false, data: []}

  constructor(private http: HttpService) {
  }

  async getBanner(){
    if(this.banner.requestSent) return
    this.banner.data = (await this.http.post({name:'car.sys.get.banner'})).data
    this.banner.requestSent = true
  }

  async getCarList(compulsive?:string){
    if(this.car.requestSent && ! compulsive) return
    const {data, success, msg} = await this.http.post({name:'car.sys.get.carlist'})
    if(!success) alert(msg)
    this.car.data = data
    this.car.requestSent = true
  }

  async addCar({province, cardNo, cardNo2, type, note, vin}){
    const {data, success, msg} = await this.http.post({
      name: 'car.sys.bind.car',
      province,
      plateNumber: cardNo,
      vin,
      engineNo: cardNo2,
      carType: type,
      description: note
    })
    this.car.requestSent = false;
    if(success) return {success:true, id: data.car_id, msg}
    else return {success:false, msg, id:''}
  }

  async deleteCar(id) {
    const {success, msg} = await this.http.post({
      name: 'car.sys.del.car',
      car_id: id
    })
    if(success) {
      // 哇神奇的bug 列表第一行去不掉…
      // const i = this.car.data.findIndex(c => c.car_id == id);
      // console.log(i)
      // this.car.data.splice(i, i);
      this.getCarList('compulsive');
    }
    return {success, msg};
  }

  async carInfo(id){
   return this.http.post({
     name: 'car.sys.search.violation',
     car_id: id
   })
  }

  async isBindId(id){
    return this.http.post({
      name: 'car.sys.is.driving.license',
      car_id: id
    })
  }

  async getOrder(){
    if(this.order.requestSent) return;
    this.order.data = (await this.http.post({
      name: 'car.get.order.list'
    })).data
    this.order.requestSent = true;
  }

}
